package org.example.smart.server;

import com.briup.smart.env.util.Backup;

import java.io.*;

public class BackupImpl implements Backup {
    @Override
    public Object load(String filePath, boolean del){
        File file = new File(filePath);
        if (!file.isFile()){
            System.out.println("备份文件不存在！");
            return null;
        }
        if(file.length() == 0){
            System.out.println("备份文件内容为空！");
            return null;
        }

        Object o = null;
        try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))){
            o = ois.readObject();
            System.out.println("已成功读取备份模块中的数据！");

        }catch (Exception e){
            e.printStackTrace();
        }
        if(del){
            boolean flag = file.delete();
            if (flag) {
                System.out.println("备份文件删除成功");
            } else {
                System.out.println("备份文件删除失败");
            }
        }
        return o;
    }

    @Override
    public void store(String filePath, Object obj, boolean append){
        try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath,append));){
            oos.writeObject(obj);
            System.out.println("成功写入备份文件" + filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
